import pygame
import random

# 初始化Pygame
pygame.init()

# 设置屏幕大小
screen_width, screen_height = 400, 400
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('贪食蛇游戏')

# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
green = (0, 255, 0)
red = (255, 0, 0)

# 设置蛇的初始位置和大小
snake_block_size = 10
snake_speed = 15

# 定义方向
direction = 'right'

# 初始化蛇的位置
snake_list = []
snake_length = 1
x1, y1 = snake_block_size * 4, snake_block_size * 4
snake_list.append((x1, y1))

# 生成食物的初始位置
food_x = round(random.randrange(0, screen_width - snake_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, screen_height - snake_block_size) / 10.0) * 10.0

# 游戏循环
game_over = False
clock = pygame.time.Clock()
font_style = pygame.font.SysFont("bahnschrift", 25)
score = 0

while not game_over:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT and direction != 'right':
                direction = 'left'
            elif event.key == pygame.K_RIGHT and direction != 'left':
                direction = 'right'
            elif event.key == pygame.K_UP and direction != 'down':
                direction = 'up'
            elif event.key == pygame.K_DOWN and direction != 'up':
                direction = 'down'

    # 更新蛇的位置
    if direction == 'right':
        x1 += snake_block_size
    elif direction == 'left':
        x1 -= snake_block_size
    elif direction == 'up':
        y1 -= snake_block_size
    elif direction == 'down':
        y1 += snake_block_size

    # 检查蛇是否吃掉了食物
    if x1 == food_x and y1 == food_y:
        food_x = round(random.randrange(0, screen_width - snake_block_size) / 10.0) * 10.0
        food_y = round(random.randrange(0, screen_height - snake_block_size) / 10.0) * 10.0
        snake_length += 1
        score += 1

    # 更新蛇的列表
    snake_head = []
    snake_head.append(x1)
    snake_head.append(y1)
    snake_list.append(snake_head)
    if len(snake_list) > snake_length:
        del snake_list[0]

    # 检查游戏结束条件
    for x in snake_list[:-1]:
        if x == snake_head:
            game_over = True

    # 绘制游戏界面
    screen.fill(black)
    pygame.draw.rect(screen, green, [food_x, food_y, snake_block_size, snake_block_size])
    for x in snake_list:
        pygame.draw.rect(screen, white, [x[0], x[1], snake_block_size, snake_block_size])

    # 显示得分
    score_text = font_style.render("Score: " + str(score), True, white)
    screen.blit(score_text, [0, 0])

    pygame.display.update()
    clock.tick(snake_speed)

# 游戏结束，显示结束信息
pygame.quit()
print("你的得分是:", score)
